package com.foodorder.repository;

import com.foodorder.entity.UserCoupon;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 用户优惠券关联数据访问接口
 */
@Repository
public interface UserCouponRepository extends JpaRepository<UserCoupon, Long> {
    
    /**
     * 根据用户ID查找优惠券
     */
    List<UserCoupon> findByUserIdAndStatus(Long userId, UserCoupon.UserCouponStatus status);
    
    /**
     * 根据用户ID查找所有优惠券
     */
    List<UserCoupon> findByUserIdOrderByReceivedAtDesc(Long userId);
    
    /**
     * 查找用户是否已领取某优惠券
     */
    Optional<UserCoupon> findByUserIdAndCouponId(Long userId, Long couponId);
    
    /**
     * 统计用户领取某优惠券的数量
     */
    long countByUserIdAndCouponId(Long userId, Long couponId);
    
    /**
     * 根据优惠券ID删除用户优惠券
     */
    void deleteByCouponId(Long couponId);
    
    /**
     * 根据状态统计用户优惠券数量
     */
    long countByStatus(UserCoupon.UserCouponStatus status);
    
    /**
     * 查找用户可用的优惠券
     */
    @Query("SELECT uc FROM UserCoupon uc " +
           "JOIN Coupon c ON uc.couponId = c.id " +
           "WHERE uc.userId = :userId AND uc.status = 'UNUSED' AND " +
           "c.status = 'ACTIVE' AND c.endTime >= CURRENT_TIMESTAMP")
    List<UserCoupon> findUserAvailableCoupons(@Param("userId") Long userId);
    
    /**
     * 查找用户在指定店铺可用的优惠券
     */
    @Query("SELECT uc FROM UserCoupon uc " +
           "JOIN Coupon c ON uc.couponId = c.id " +
           "WHERE uc.userId = :userId AND uc.status = 'UNUSED' AND " +
           "c.status = 'ACTIVE' AND c.endTime >= CURRENT_TIMESTAMP AND " +
           "(c.storeId = :storeId OR c.storeId IS NULL)")
    List<UserCoupon> findUserAvailableCouponsForStore(@Param("userId") Long userId, 
                                                     @Param("storeId") Long storeId);
    
    /**
     * 根据优惠券ID查找用户优惠券
     */
    List<UserCoupon> findByCouponId(Long couponId);
}